# import fitz

# def bookmarks_get(source: str) -> None:
#     with fitz.open(source) as doc:
#         toc = doc.get_toc()
#     print(toc)

# if __name__ == '__main__':
#     pdf = "./rl.pdf"
#     bookmarks_get(pdf)

import fitz  # PyMuPDF

class PDFContextManager:
    def __init__(self, pdf_path):
        self.pdf_path = pdf_path
        self.doc = None

    def __enter__(self):
        """打开 PDF 文件"""
        self.doc = fitz.open(self.pdf_path)
        return self  # 返回上下文管理器实例

    def __exit__(self, exc_type, exc_value, traceback):
        """关闭 PDF 文件"""
        if self.doc:
            self.doc.close()

    def get_bookmarks_and_links(self):
        """获取书签和其链接的偏移位置"""
        toc = self.doc.get_toc()  # 获取目录（书签）

        # 遍历目录项
        for item in toc:
            level = item[0]
            title = item[1]
            page_number = item[2]  # 目标页码

            # 获取目标页的链接
            page = self.doc.load_page(page_number)  # 加载目标页
            links = page.get_links()  # 获取页中的所有链接

            # 查找与书签标题相关的链接
            for link in links:
                # 根据 link 字典的结构判断是否是跳转链接，并且处理对应的链接
                if link.get("kind") == 4:  # 识别跳转到命名目标的链接
                    nameddest = link.get("nameddest")
                    if nameddest:
                        print(f"书签 '{title}' 的跳转链接为 '{nameddest}'，位于第 {page_number + 1} 页，位置: {link['from']}")

# 使用上下文管理器
pdf_path = './rl.pdf'
with PDFContextManager(pdf_path) as pdf_manager:
    pdf_manager.get_bookmarks_and_links()

